<template>
  <div class="t-calendar">
    <div class="t-calendar-main">
      <div class="t-calendar-operation"><slot name="header"></slot></div>
      <div class="t-calendar-style">
        <ul class="t-calendar-header">
          <li v-for="(item, index) in THeader" :key="index">
            {{ item }}
          </li>
        </ul>
        <div class="t-calendar-day">
          <template v-if="TBody.length">
            <div
                class="t-calendar-row"
                v-for="(item, index) in TBody"
                :key="index"
            >
              <div
                  class="t-calendar-col"
                  v-for="(col, colIdx) in item"
                  :key="colIdx"
                  :class="getDayClass(col)"
                  :style="getDayStyle(col)"
              >
                <CalendarItem
                    :col="col"
                    :time="selectedTime"
                    @changeTargetDate="changeDate"
                ></CalendarItem>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="no-date">抱歉,暂无数据</div>
          </template>
          <div class="t-calendar-mark">
            {{ props.time.split('-')[1] }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, ref, watch } from 'vue';

import DateClass from './DateClass';
import Calendar from './Calendar';
import CalendarItem from './calendarItem.vue';

import { dateBase } from './Calendar';

const props = defineProps({
  color: {
    type: String,
    default: '#f5f5f5',
  },
  time: {
    type: String,
    default: '2022-01-01',
  },
  isReset: {
    type: Boolean,
    default: false,
  },
  // 学期标记数据（当前月的开始/结束日期）
  termMarks: {
    type: Array,
    default: () => [] as Array<{
      date: string; // YYYY-MM-DD
      type: 'start' | 'end';
      termId: string;
      color: string;
    }>
  }
});

const THeader = Calendar.title();

const selectedTime = ref(props.time);
const TBody = computed(() =>
    Calendar.table(DateClass.changeTimeStr(props.time))
);

const emit = defineEmits(['getDate']);

function changeDate(time: dateBase) {
  selectedTime.value = time.date;
  emit('getDate', time);
}

watch(
    () => props.isReset,
    () => (selectedTime.value = props.time)
);

// 获取日期的CSS类
function getDayClass(col: any) {
  const classes = [];
  if (col?.otherMonth) {
    classes.push('other-month');
  }
  return classes;
}

// 修改getDayStyle函数，添加日志
function getDayStyle(col: any) {
  const styles: Record<string, string> = {};
  if (!col?.dateObj) return styles;

  // 格式化当前日期为 YYYY-MM-DD
  const currentDate = formatDateForComparison(col.dateObj);
  console.log(`检查日期 ${currentDate} 的标记`);

  // 遍历当前月的学期标记，匹配则添加下划线
  props.termMarks.forEach(mark => {
    if (mark.date === currentDate) {
      console.log(`匹配到标记：${currentDate}，颜色：${mark.color}`);
      styles.borderBottom = `2px solid ${mark.color}`;
      styles.paddingBottom = '2px';
      styles.fontWeight = '500';
    }
  });

  return styles;
}

// 格式化日期用于比较
function formatDateForComparison(dateObj: Date): string {
  if (!dateObj) return '';
  const year = dateObj.getFullYear();
  const month = String(dateObj.getMonth() + 1).padStart(2, '0');
  const day = String(dateObj.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}
</script>

<style scoped="scoped" lang="less">
@light-line: #ebeef5;
:deep(.t-calendar-col) {
  position: relative !important;
  // 确保下划线不会被内边距遮挡
  padding-bottom: 2px !important;
  // 优先显示动态绑定的边框样式
  border-bottom: inherit !important;
  font-weight: inherit !important;
}
.t-calendar {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;

  & > div {
    position: relative;
    height: 100%;
    box-sizing: border-box;
  }

  .t-calendar-main {
    flex: 1;

    .t-calendar-operation {
      height: 26px; // 缩小头部高度
    }

    .t-calendar-style {
      position: relative;
      width: 100%;
      height: calc(~'100% - 26px'); // 调整高度计算

      .t-calendar-header {
        position: relative;
        display: flex;
        width: 100%;
        height: 26px; // 适配主组件周头高度
        padding: 0;
        box-sizing: border-box;

        li {
          position: relative;
          display: flex;
          align-items: center;
          justify-content: center;
          flex: 1;
          font-size: 12px; // 调整字体大小
        }
      }

      .t-calendar-day {
        position: relative;
        display: flex;
        flex-direction: column;
        width: 100%;
        height: calc(~'100% - 26px'); // 调整高度计算

        .t-calendar-row {
          position: relative;
          width: 100%;
          height: 26px; // 与主组件日期格子高度对齐
          display: flex;
          flex: 1;
          z-index: 10;
          border-bottom: 1px solid @light-line;

          .t-calendar-col {
            position: relative;
            box-sizing: border-box;
            flex: 1;
            border-left: 1px solid @light-line;
            padding: 1px; // 减少内边距
            font-size: 8px; // 减小字体
            transition: all 0.2s;

            &.other-month {
              opacity: 0.6;
            }
          }

          .t-calendar-col:last-child {
            border-right: 1px solid @light-line;
          }
        }

        .t-calendar-row:first-child {
          border-top: 1px solid @light-line;
        }

        .no-date {
          position: relative;
          width: 100%;
          height: 100%;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 12px; // 调整字体
        }

        .t-calendar-mark {
          position: absolute;
          display: flex;
          justify-content: center;
          align-items: center;
          width: 100%;
          height: 100%;
          box-sizing: border-box;
          font-size: 6rem !important; // 大幅缩小背景月份
          color: #ebeef5;
          opacity: 0.5;
          z-index: 0;
        }
      }
    }
  }
}
</style>
